<?php
/**
 * @author GhostWei
 * @date Sep 29, 2012
 */
abstract class translator_abstract {
	
	protected $adapter = null;
	protected $cookiejar = null;
	
	public function get($url, $returnHeader = false) {
		curl_setopt($this->getAdapter(), CURLOPT_URL, $url);
		curl_setopt($this->getAdapter(), CURLOPT_POST, false);
		$this->setCookieJar();
		curl_setopt($this->getAdapter(), CURLOPT_HEADER, $returnHeader);
		return curl_exec($this->getAdapter());
	}
	
	public function post($url, $parameters = array(), $returnHeader = false) {
		curl_setopt($this->getAdapter(), CURLOPT_URL, $url);
		curl_setopt($this->getAdapter(), CURLOPT_POST, true);
		$this->setCookieJar();
		curl_setopt($this->getAdapter(), CURLOPT_POSTFIELDS, $parameters);
		curl_setopt($this->getAdapter(), CURLOPT_HEADER, $returnHeader);
		return curl_exec($this->getAdapter());
	}
	
	protected function setAdapter($adapter = null) {
		if(null == $adapter) {
			$this->adapter = curl_init();
			curl_setopt($this->adapter, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($this->adapter, CURLOPT_SSL_VERIFYPEER, false);
		} else {
			$this->adapter = $adapter;
		}
	}
	
	protected function getAdapter() {
		return $this->adapter;
	}
	
	protected function setCookieJar() {
		if($this->cookiejar == null) {
			$this->cookiejar = tempnam(_DIRECTORY_VAR . '/tmp', 'TRANSLATOR');
		}
		curl_setopt($this->getAdapter(), CURLOPT_COOKIEFILE, $this->cookiejar);
		curl_setopt($this->getAdapter(), CURLOPT_COOKIEJAR, $this->cookiejar);
	}
	
	public function __construct() {
		$this->setAdapter();
	}
	
	public function __destruct() {
		@unlink($this->cookiejar);
	}
	
	protected $_from = null;
	/**
	 *
	 * @return translator_abstract
	 */
	public function setFrom($from) {
		$this->_from = $from;
		return $this;
	}
	public function getFrom() {
		return $this->_from;
	}
	
	protected $_to = null;
	/**
	 *
	 * @return translator_abstract
	 */
	public function setTo($to) {
		$this->_to = $to;
		return $this;
	}
	public function getTo() {
		return $this->_to;
	}
	
	protected $_text = null;
	/**
	 *
	 * @return translator_abstract
	 */
	public function setText($text) {
		$this->_text = $text;
		return $this;
	}
	public function getText() {
		return $this->_text;
	}
	
	/**
	 *
	 * @return system_setting_translator
	 */
	protected function getConcept($name) {
		$concept = new system_setting_translator($name);
		$languages = $concept->getLanguage();
		if(!in_array($this->getFrom(), array_keys($languages))) {
			throw new translator_exception("Translator is not supports language: {$this->getFrom()}");
		}
		if(!in_array($this->getTo(), array_keys($languages))) {
			throw new translator_exception("Translator is not supports language: {$this->getTo()}");
		}
		return $concept;
	}
	
	/**
	 *
	 * @return translator_response
	 */
	abstract public function translate();

}

